const { Paragraph, TextRun, Table, TableRow, TableCell, CheckBox, ShadingType } = require("docx");
const { AlignmentType } = require("docx");
const { getAlignment, getIndentValue, convertLengthToTwips, mapFontSizeToHalfPoints } = require("../common/utils");

function generateCriteriaTable(field, baseIndent = 0) {
    const { value } = field;
    const finalIndent = getIndentValue(value.alignment, baseIndent);
    
    if (!value.columns || value.columns.length === 0) {
        return [];
    }
    
    const tableRows = [];
    const sizeHalfPoints = mapFontSizeToHalfPoints(value.fontSize);
    
    // 表头行
    tableRows.push(
        new TableRow({
            children: value.columns.map((column) => {
                const defaultHeaderWidth = column.type === 'number' ? 1200 : 2000; // twips fallback
                return new TableCell({
                    children: [
                        new Paragraph({
                            alignment: AlignmentType.CENTER,
                            spacing: { line: 360 },
                            children: [
                                new TextRun({
                                    text: column.title || column.id,
                                    size: sizeHalfPoints,
                                    bold: (column.isBold ?? value.isBold ?? false),
                                    font: "SimSun" // 宋体
                                })
                            ]
                        })
                    ],
                    // 表头浅灰底色：由 headerShading 开关控制
                    shading: value.headerShading ? {
                        type: ShadingType.CLEAR,
                        color: "auto",
                        fill: "EEEEEE"
                    } : undefined,
                    width: {
                        size: convertLengthToTwips(column.widthCm, defaultHeaderWidth),
                        type: "dxa"
                    },
                    verticalAlign: AlignmentType.CENTER,
                });
            })
        })
    );
    
    // 数据行
    if (value.rows && value.rows.length > 0) {
        value.rows.forEach((row, rowIndex) => {
            tableRows.push(
                new TableRow({
                    children: value.columns.map(column => {
                        const cellValue = row[column.id];
                        let cellContent;
                        let cellChildren;

                        switch (column.type) {
                            case 'number':
                                // 序号列：若单元格未显式设置值，则使用行号（从1开始）
                                cellContent = new Paragraph({
                                    alignment: AlignmentType.CENTER,
                                    spacing: { line: 360 },
                                    children: [
                                        new TextRun({
                                            text: (cellValue !== undefined && cellValue !== null && String(cellValue) !== '') ? String(cellValue) : String(rowIndex + 1),
                                            size: 21,
                                            font: "SimSun"
                                        })
                                    ]
                                });
                                break;
                            case 'radio':
                                // 单选：每个选项单独一段落，便于按选项换行
                                const radioOptions = row.options && row.options[column.id] ? row.options[column.id] : column.options;
                                cellChildren = (radioOptions || []).map(option => new Paragraph({
                                    alignment: AlignmentType.LEFT,
                                    spacing: { line: 360 },
                                    children: [
                                        new CheckBox({
                                            checked: option.value === cellValue,
                                            size: 24
                                        }),
                                        new TextRun({
                                            text: ' ' + (option.label || ''),
                                            size: sizeHalfPoints,
                                            font: "SimSun"
                                        })
                                    ]
                                }));
                                break;
                                
                            case 'checkbox':
                                // 复选框：每个选项单独一段落，实现同一单元格内按选项换行
                                const checkboxOptions = row.options && row.options[column.id] ? row.options[column.id] : column.options;
                                cellChildren = (checkboxOptions || []).map(option => new Paragraph({
                                    alignment: AlignmentType.LEFT,
                                    spacing: { line: 360 },
                                    children: [
                                        new CheckBox({
                                            checked: Array.isArray(cellValue) && cellValue.includes(option.value),
                                            size: 24
                                        }),
                                        new TextRun({
                                            text: ' ' + (option.label || ''),
                                            size: sizeHalfPoints,
                                            font: "SimSun"
                                        })
                                    ]
                                }));
                                break;
                                
                            default:
                                // 文本/多行文本：按行渲染为多个段落，使其在单元格内自动换行
                                if (column.type === 'textarea') {
                                    const lines = Array.isArray(cellValue) ? cellValue : (cellValue ? [String(cellValue)] : []);
                                    cellChildren = (lines.length > 0 ? lines : ['']).map(line => new Paragraph({
                                        alignment: AlignmentType.LEFT,
                                        spacing: { line: 360 },
                                        children: [
                                            new TextRun({
                                                text: line || '',
                                                size: sizeHalfPoints,
                                                font: "SimSun"
                                            })
                                        ]
                                    }));
                                } else {
                                    // 其他文本/数字类型：根据整体 textAlign 控制对齐（默认 left）
                                    const align = (value.textAlign === 'center') ? AlignmentType.CENTER : AlignmentType.LEFT;
                                    cellContent = new Paragraph({
                                        alignment: align,
                                        spacing: { line: 360 },
                                        children: [
                                            new TextRun({
                                                text: cellValue || '',
                                                size: sizeHalfPoints,
                                                font: "SimSun" // 宋体
                                            })
                                        ]
                                    });
                                }
                        }

                        return new TableCell({
                            children: cellChildren ? cellChildren : [cellContent],
                            width: {
                                size: convertLengthToTwips(column.widthCm, 2000),
                                type: "dxa"
                            },
                            verticalAlign: AlignmentType.CENTER,
                        });
                    })
                })
            );
        });
    } else {
        // 如果没有数据行，创建一个空行
        tableRows.push(
            new TableRow({
                children: value.columns.map(column => 
                    new TableCell({
                        children: [
                            new Paragraph({
                                alignment: AlignmentType.CENTER,
                                spacing: { line: 360 },
                                children: [
                                    new TextRun({
                                        text: '',
                                        size: 21,
                                        font: "SimSun"
                                    })
                                ]
                            })
                        ],
                        width: {
                            size: convertLengthToTwips(column.widthCm, 2000),
                            type: "dxa"
                        },
                        verticalAlign: AlignmentType.CENTER,
                    })
                )
            })
        );
    }
    
    const table = new Table({
        rows: tableRows,
        width: {
            size: 100,
            type: "pct"
        },
        indent: {
            size: finalIndent,
            type: "dxa",
        }
    });
    
    const elements = [];

    // 标题已废弃：不再渲染表格标题

    elements.push(table);
    
    // 如果有说明文字，添加说明
    if (value.note && value.note.trim()) {
        elements.push(
            new Paragraph({
                indent: { left: finalIndent },
                alignment: getAlignment(value.alignment),
                spacing: { before: 50, after: 100, line: 360 },
                children: [
                    new TextRun({
                        text: value.note,
                        size: 20,
                        font: "SimSun", // 宋体
                        italics: true
                    })
                ]
            })
        );
    }
    
    return elements;
}

module.exports = {
    generateCriteriaTable
}; 